import store from "@/store/index.js"
import {
	getcode_h5
} from "@/api/login.js"

const $Toast = {
	none: (str, time = 1500) => {
		return new Promise((resolve, reject) => {
			uni.showToast({
				title: str,
				icon: "none",
				duration: time,
				success: () => {
					setTimeout(() => {
						resolve()
					}, time)
				}
			})
		})
	},
	success: (str, time = 1500) => {
		return new Promise((resolve, reject) => {
			uni.showToast({
				title: str,
				icon: "success",
				duration: time,
				success: () => {
					setTimeout(() => {
						resolve()
					}, time)
				}
			})
		})
	},
	loading: (str, time = 1500) => {
		return new Promise((resolve, reject) => {
			uni.showToast({
				title: str,
				icon: "loading",
				duration: time,
				success: () => {
					setTimeout(() => {
						resolve()
					}, time)
				}
			})
		})
	}
}
const get_request = function(key) {
	var url = location.search; //获取url中"?"符后的字串
	if (url.indexOf("?") != -1) {
		var str = url.substr(1);
		var strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			let _k = strs[i].split("=")[0];
			if (_k == key) {
				return decodeURIComponent(strs[i].split("=")[1]);
			}
			// theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
		}
		return null;
	}
}
const _wx = {
	is_wx: function() {
		var ua = navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i) == "micromessenger") {
			return true;
		} else {
			return false;
		}
	},
	get_code() {
		const code = get_request('code');
		if (code) {
			return code;
		}
		const appid = "wxf656c37af142a308";
		const back_url = encodeURIComponent(window.location.href);
		const url =
			`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${back_url}&response_type=code&scope=snsapi_userinfo&state=get_openid#wechat_redirect`;
		window.location.replace(url);
	},
	get_info(code) {
		return new Promise(resolve => {
			getcode_h5({
				code
			}).then(res => {
				resolve(res.data);
			})
		})
	},
	async set_wx_info() {
		const code = this.get_code();
		if (!code) {
			return false;
		}
		const res = await this.get_info(code);

		console.log('wx-res')
		console.log(res)

		const {
			token,
			userInfo,
			wx_info
		} = res;
		store.commit("setOpenid", wx_info.openid)
		store.commit("setUnionid", wx_info.unionid)
		if (token) {
			store.commit("setToken", token)
			store.commit("setHasRegister", true)
		}
		if (!(JSON.stringify(userInfo) === "[]" || !userInfo)) {
			store.commit("setUserInfo", userInfo)
		}
		if (wx_info && (JSON.stringify(userInfo) === "[]" || !userInfo)) {
			store.commit("setwxuserinfo", wx_info)
		}
	},
	// share_wx(data) {
	// 	wx.updateAppMessageShareData({
	// 		...data
	// 	})
	// 	wx.updateTimelineShareData({
	// 		...data
	// 	})
	// }
}

export {
	$Toast,
	_wx
}
